package com.turing.selfwebservice.common;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter implements Filter {

	private static Logger log = Logger.getLogger("CharacterEncodingFilter");
	private static final String DEFAULT_ENCODING = "UTF-8";
	protected String encoding;
	protected FilterConfig filterConfig;
	protected boolean ignore;

	public CharacterEncodingFilter() {
		encoding = null;
		filterConfig = null;
		ignore = true;
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		log.fine("SetCharacterEncodingFilter.doFilter()");
		try {
			if (ignore || request.getCharacterEncoding() == null)
				if (encoding != null) {
					request.setCharacterEncoding(encoding);
					response.setContentType("text/html; charset=" + encoding);
				} else {
					request.setCharacterEncoding(DEFAULT_ENCODING);
					response.setContentType("text/html; charset="
							+ DEFAULT_ENCODING);
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
		chain.doFilter(request, response);
	}

	/**
	 * Do redirect.
	 * 
	 * @param uri
	 *            String
	 * @param request
	 *            the HttpServletRequest object
	 * @param response
	 *            the HttpServletResponse object we needed to perform redirect
	 * @throws IOException
	 */
	private void redirect(String uri, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		/** only prepend context path for relative path */
		if (uri.startsWith("/")) {
			uri = request.getContextPath() + uri;
		}
		response.sendRedirect(response.encodeRedirectURL(uri));
	}

	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		log
				.info("SetCharacterEncodingFilter init, now Set Character Encoding for each request.");
		this.filterConfig = filterConfig;
		encoding = filterConfig.getInitParameter("encoding");
		String value = filterConfig.getInitParameter("ignore");
		if (value == null)
			ignore = true;
		else if (value.equalsIgnoreCase("true"))
			ignore = true;
		else if (value.equalsIgnoreCase("yes"))
			ignore = true;
		else
			ignore = false;
	}

	public void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

}
